﻿namespace SharpGym.Silverlight.Views.Aluno
{
    using System;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using SharpService;

    public partial class NewAluno : INotifyPropertyChanged
    {
        // Using a DependencyProperty as the backing store for Busy.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BusyProperty =
            DependencyProperty.Register("Busy", typeof (BusyIndicator), typeof (NewAluno), null);


        private AlunoDto aluno;


        public NewAluno()
        {
            InitializeComponent();
        }

        public BusyIndicator Busy
        {
            get { return (BusyIndicator) GetValue(BusyProperty); }
            set { SetValue(BusyProperty, value); }
        }

        public AlunoDto Aluno
        {
            get
            {
                DateTime dateTime;

                DateTime.TryParse(AniversarioBox.Text, out dateTime);

                return aluno ??
                       (aluno =
                        new AlunoDto
                            {
                                Nome = NomeBox.Text,
                                DataNascimento = dateTime.Ticks,
                                Telefone = TelefoneBox.Text
                            });
            }

            set
            {
                aluno = value;
                OnPropertyChanged("Aluno");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Busy.IsBusy = true;
            App.Client.CreateAlunoAsync(Aluno);
            App.Client.CreateAlunoCompleted += ClientOnCreateAlunoCompleted;
        }

        private void ClientOnCreateAlunoCompleted(object sender,
                                                  CreateAlunoCompletedEventArgs createAlunoCompletedEventArgs)
        {
            App.Client.CreateAlunoCompleted -= ClientOnCreateAlunoCompleted;
            Busy.IsBusy = false;

            if (createAlunoCompletedEventArgs.Error != null) return;

            MessageBox.Show("Aluno Adicionado");
            Busy.DataContext = new Random().Next();
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}